<template>
  <view class="home">
    <view class="top-main">
      <view class="top-fixed">
        <view class="seat"></view>
        <view class="top-nav">
          <view class="logo-name">中科云采</view>
        </view>
        <view class="shop-name" v-if="$store.state.user.storeInfo.name">{{
          $store.state.user.storeInfo.name
        }}</view>
        <view
          class="shop-name u-flex u-flex-items-center"
          @click="onRegisterStore"
          v-else
        >
          去注册商户
          <u-icon name="arrow-right" color="#ffffff" size="14"></u-icon>
        </view>
        <view class="search-box">
          <view class="search-left" @click="onScanCode">
            <image
              class="icon"
              src="@/static/images/icon/icon_sys.png"
              mode="aspectFill"
            ></image>
          </view>
          <view class="search">
            <up-search
              placeholder="搜索商品名称/条形码"
              v-model="keyword"
              height="30"
              bgColor="#ffffff"
              :showAction="false"
              disabled
              @click="onJumpSearch('search')"
            ></up-search>
          </view>
          <view class="search-right" @click="onReplenish">
            <image
              class="icon"
              src="@/static/images/icon/icon_bh.png"
              mode="aspectFill"
            ></image>
            <view class="search-right-text">快速补货</view>
          </view>
        </view>
      </view>
      <view class="fixed-bottom" :class="{ show: isShowBg }"></view>
      <view class="top-poster">
        <image
          class="top-poster-image"
          src="@/static/852x364.png"
          mode="aspectFill"
        ></image>
      </view>
    </view>
    <view class="special-offer">
      <image
        class="top-poster-image"
        src="@/static/poster-2.jpg"
        mode="aspectFill"
      ></image>
    </view>
    <view class="banner-main">
      <up-swiper
        :list="bannerList"
        indicator
        indicatorMode="line"
        circular
        @click="onSwiperClick"
        height="148"
        radius="10"
      ></up-swiper>
    </view>

    <view class="welcome-main">
      <image
        class="welcome"
        src="@/static/welcome.png"
        mode="heightFix"
      ></image>
    </view>
    <view class="navbar-main">
      <view
        class="navbar-item-1"
        v-for="(item, index) in navbar_list_1"
        :key="index"
        @click="onJumpPage(item)"
      >
        <view class="navbar-icon">
          <image
            v-if="item.image_url"
            class="navbar-icon"
            :src="item.image_url"
            mode="aspectFill"
          ></image>
        </view>
        <view class="navbar-name">{{ item.name }}</view>
      </view>
      <view
        class="navbar-item-2"
        v-for="(item, index) in navbar_list_2"
        :key="index"
        @click="onJumpSearch('categorize', item)"
      >
        <image
          v-if="item.image_url"
          class="navbar-icon"
          :src="item.image_url"
          mode="aspectFill"
        ></image>
        <view v-else class="navbar-icon"></view>
        <view class="navbar-name">{{ item.name }}</view>
      </view>
    </view>
    <view class="poster-main">
      <image class="poster" src="@/static/poster.png" mode="aspectFill"></image>
    </view>

    <view class="product-main" :class="{ 'p-t80': isNavFixed }">
      <view class="product-navbar" :class="{ 'navbar-fixed': isNavFixed }">
        <view
          class="navbar-item"
          :class="{ active: active == 0 }"
          @click="onProductChange(0)"
          >新品推荐</view
        >
        <view
          class="navbar-item"
          :class="{ active: active == 1 }"
          @click="onProductChange(1)"
          >收银必备</view
        >
        <view
          class="navbar-item"
          :class="{ active: active == 2 }"
          @click="onProductChange(2)"
          >热销商品</view
        >
        <view
          class="navbar-item"
          :class="{ active: active == 3 }"
          @click="onProductChange(3)"
          >本周推荐</view
        >
      </view>
      <div class="product-list">
        <my-waterfalls-flow
          ref="waterfallsFlowRef"
          :value="productList"
          :column="2"
          :columnSpace="1.5"
          :seat="2"
          imageKey="image_url"
        >
          <!-- #ifdef MP-WEIXIN -->
          <view
            class="demo-warter"
            v-for="(item, index) in productList"
            :key="index"
            slot="slot{{index}}"
          >
            <view class="demo-title">
              {{ item.name }}
            </view>
            <view class="sub_title"
              >{{ item.min_sale_quantity }} {{ item.uom.name }}起订</view
            >
            <view class="product-bottom">
              <view class="demo-price"
                >￥{{ item.sale_price ? item.sale_price : "???" }}</view
              >
              <!-- <view
                class="add-cart"
                v-if="!isCart(item.id)"
                @click.stop="handleOpenVariant(item)"
              >
                <up-icon
                  name="plus-circle-fill"
                  size="26"
                  color="#3cb9ef"
                ></up-icon>
              </view> -->

              <!-- <view class="num-step" @tap.stop v-else>
                <up-number-box
                  v-if="checkCart[item.id]"
                  :model-value="checkCart[item.id].num"
                  :min="0"
                  :step="1"
                  :long-press="false"
                  integer
                  disabledInput
                >
                  <template #minus>
                    <view class="minus" @click="toCart">
                      <up-icon name="minus" color="#999999" size="14"></up-icon>
                    </view>
                  </template>
                  <template #input>
                    <text class="qty-input">{{ checkCart[item.id].num }}</text>
                  </template>
                  <template #plus>
                    <view class="plus" @click="handleOpenVariant(item)">
                      <up-icon name="plus" color="#ffffff" size="14"></up-icon>
                    </view>
                  </template>
                </up-number-box>
              </view> -->
            </view>
          </view>
          <!-- #endif -->
        </my-waterfalls-flow>
      </div>

      <up-loadmore
        bg-color="rgb(240, 240, 240)"
        :status="loadStatus"
      ></up-loadmore>
    </view>
    <up-popup
      :show="couponPopupShow"
      :safeAreaInsetBottom="false"
      mode="bottom"
      :round="10"
      closeable
      :closeOnClickOverlay="false"
      @close="couponPopupShow = false"
    >
      <view class="p-20">
        <u-text align="center" text="领取优惠券" size="18" bold></u-text>
      </view>
      <view class="p-20">
        <scroll-view scroll-y style="height: 650rpx">
          <my-coupon
            v-for="coupon in notTakeCouponList"
            :key="coupon.id"
            :data="coupon"
          ></my-coupon>
        </scroll-view>
        <u-gap height="10"></u-gap>
        <u-button type="primary" @click="takeAllCoupon">一键领取</u-button>
      </view>
    </up-popup>
    <my-variants
      :productId="currentProductId"
      v-model:show="variantShow"
    ></my-variants>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { route } from "@/uni_modules/uview-plus";
import { onPageScroll, onReachBottom, onShow } from "@dcloudio/uni-app";
import { categories, goodsList } from "@/common/apis/goods.js";
import { canNextForStore } from "@/util";
import { useStore } from "vuex";

const store = useStore();

import banner1 from "@/static/images/banner/banner1.png";

const variantShow = ref(false);
const currentProductId = ref(0);

const couponPopupShow = ref(false);
const keyword = ref("");
const bannerList = ref([banner1]);
const isShowBg = ref(false);
const isNavFixed = ref(false);
const navbar_list_1 = ref([
  {
    name: "快速补货",
    url: "/pages/order/replenish",
    image_url: "/static/images/icon/buhuo.png",
  },
  {
    name: "促销专区",
    icon: "icon-cuxiaohuodong",
    url: "/pages/goods/activity",
    image_url: "/static/images/icon/cuxiao.png",
  },
  {
    name: "折扣专区",
    icon: "icon-zhekou",
    image_url: "/static/images/icon/zhekou.png",
  },
  {
    name: "全部商品",
    url: "/pages/goods/list",
    image_url: "/static/images/icon/shangpin.png",
  },
]);
const navbar_list_2 = ref([]);
const active = ref(0);
const productList = ref([]);
const params = reactive({
  page: 1,
  size: 10,
});
const totalPage = ref(0);
const loadStatus = ref("nomore");

function onRegisterStore() {
  route({
    url: "pages/app/store",
  });
}
function onSwiperClick() {}
function onProductChange(val) {
  active.value = val;
}
async function onJumpPage(row) {
  if (row.url) {
    if (row.url == "/pages/order/replenish") {
      const result = await canNextForStore();
      if (!result) {
        return;
      }
    }
    uni.navigateTo({
      url: row.url,
    });
  }
}

function onScanCode() {
  // 调起条码扫描
  uni.scanCode({
    scanType: ["barCode"],
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      uni.navigateTo({
        url: "/pages/goods/list?type=search&keyword=" + res.result,
      });
    },
    fail: function (err) {
      console.log(err);
      uni.showToast({
        title: "识别失败",
        icon: "error",
      });
    },
  });
}

function onJumpSearch(type, row) {
  if (type == "search") {
    route({
      url: "/pages/app/search",
    });
  } else if (type == "categorize" && row) {
    route({
      url: "/pages/goods/list",
      params: {
        type: type,
        categorizeId: row.id,
        categorizeName: row.name,
      },
    });
  }
}

// 检测是否为购物车商品
function isCart(id) {
  return Object.keys(checkCart.value).includes(id + "");
}
// 检测商品在购物车中的下标
function checkGoodsIndex(id) {
  let cIndex = 0;
  cartList.value.forEach((item, index) => {
    if (id == item.product.id) {
      cIndex = index;
    }
  });
  return cIndex;
}

// 更改商品数
async function onChangeNum(e, item) {
  let gIndex = checkGoodsIndex(item.id);
  if (e.value < item.min_sale_quantity) {
    uni.showModal({
      title: "删除提示",
      confirmColor: "#f0c785",
      content: `是否确认从购物车中删除此商品?`,
      success: (res) => {
        if (res.confirm) {
          store.dispatch("fetchDelCart", checkCart.value[item.id].cartOrderId);
        } else {
          checkCart.value[item.id].num = item.min_sale_quantity;
        }
      },
    });
  } else if (e.value != checkCart.value[item.id].num) {
    uni.showLoading({
      mask: true,
    });
    const qty =
      e.value > checkCart.value[item.id].num
        ? "+" + item.min_sale_quantity
        : "-" + item.min_sale_quantity;
    await store.dispatch("fetchAddCart", {
      product_id: item.id,
      quantity: qty,
    });
    uni.hideLoading();
  }
}
//加入购物车
function addCart(row) {
  if (row.stock > row.min_sale_quantity) {
    store.dispatch("fetchAddCart", {
      product_id: row.id,
      quantity: row.min_sale_quantity,
    });
  } else {
    uni.$u.toast("库存不足");
  }
}

async function getCategories() {
  const response = await categories({ is_index: 1 });
  navbar_list_2.value = response;
}
/**
 * @description 获取商品列表
 */
async function fetchGoodsList() {
  const response = await goodsList(params);
  productList.value =
    params.page == 1
      ? response.records
      : productList.value.concat(response.records);
  totalPage.value = response.total_page;
  loadStatus.value = params.page >= response.total_page ? "nomore" : "loadmore";
}

const notTakeCouponList = ref([]);

/**
 * @description 获取未领取的优惠券列表
 * @returns {Promise<void>}
 */
async function getNotTakeCouponList() {
  // 调用 store 中的 action 获取未领取的优惠券列表
  const response = await store.dispatch("fetchNotTakeCouponList");
  // 检查响应是否存在且记录数组不为空
  if (response && response.records.length) {
    // 将未领取的优惠券记录赋值给 notTakeCouponList
    notTakeCouponList.value = response.records.filter((i) => !i.has_get);
    // 如果未领取的优惠券列表不为空，显示优惠券弹窗
    if (notTakeCouponList.value.length) {
      // 显示优惠券弹窗
      couponPopupShow.value = true;
    }
  }
}

async function takeAllCoupon() {
  const promises = [];
  notTakeCouponList.value.forEach((item) => {
    promises.push(store.dispatch("fetchTakeCoupon", item.id));
  });
  await Promise.all(promises);
  couponPopupShow.value = false;
  uni.showToast({
    title: "领取成功",
    icon: "success",
  });
  store.dispatch("fetchCouponList");
}

onMounted(async () => {
  getCategories();
  fetchGoodsList();
  if (store.state.user.isStore) {
    await getNotTakeCouponList();
  }
});

onPageScroll((e) => {
  if (e.scrollTop >= 50) {
    isShowBg.value = true;
  } else {
    isShowBg.value = false;
  }

  if (e.scrollTop >= 875) {
    isNavFixed.value = true;
  } else {
    isNavFixed.value = false;
  }
});

const cartList = computed(() => {
  return store.state.cart.list;
});
const checkCart = computed(() => {
  return store.state.cart.checkCart;
});
const storeInfo = computed(() => {
  return store.state.user.storeInfo || "";
});
async function onReplenish() {
  const result = await canNextForStore();
  uni.$u.route({
    url: "/pages/order/replenish",
  });
}

function toCart() {
  uni.redirectTo({
    url: "/pages/index/cart",
  });
}

function handleOpenVariant(product) {
  currentProductId.value = product.id;
  variantShow.value = true;
}

onReachBottom(() => {
  if (loadStatus.value == "nomore") return;
  params.page++;
  fetchGoodsList();
});
</script>

<style lang="scss" scoped>
.home {
  .top-main {
    padding: 0 20rpx;
    height: 580rpx;
    background-image: linear-gradient(
      to bottom,
      #44bdf1 60%,
      rgba(8, 218, 245, 0)
    );
    padding-top: 280rpx;
    box-sizing: border-box;

    .top-fixed {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      padding: 0 20rpx;
      background-color: #44bdf1;
      z-index: 1;
    }

    .fixed-bottom {
      position: fixed;
      left: 0;
      right: 0;
      top: 280rpx;
      z-index: -10;
      height: 500rpx;
      background-image: linear-gradient(
        to bottom,
        #44bdf1,
        rgba(8, 218, 245, 0)
      );
      opacity: 0;
      transition: all ease 1s;

      &.show {
        opacity: 1;
      }
    }

    .top-nav {
      padding-top: 50rpx;
      height: 60rpx;
      display: flex;
      align-items: center;

      .logo-name {
        color: #ffffff;
        font-weight: bold;
        font-size: 28rpx;
      }
    }

    .shop-name {
      color: #ffffff;
      margin-bottom: 10rpx;
    }

    .search-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20rpx;

      .search {
        flex: 1;
        margin: 0 20rpx;
      }

      .search-right {
        display: flex;
        align-items: center;

        .search-right-text {
          width: 48rpx;
          color: #ffffff;
          line-height: 26rpx;
          font-size: 24rpx;
          margin-left: 10rpx;
        }
      }

      .icon {
        width: 60rpx;
        height: 60rpx;
        display: block;
      }
    }

    .top-poster-image {
      width: 100%;
      height: 268rpx;
    }
  }

  .special-offer {
    padding: 0 20rpx;

    image {
      width: 100%;
      height: 288rpx;
      border-radius: 10rpx;
    }
  }

  .banner-main {
    padding: 0 20rpx;
    margin-bottom: 20rpx;
  }

  .welcome-main {
    text-align: center;

    .welcome {
      height: 138rpx;
    }
  }

  .navbar-main {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    padding: 0 20rpx;
    margin-bottom: 20rpx;

    .navbar-item-1 {
      padding: 10rpx 0;
      width: calc(100% / 4);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

    .navbar-item-2 {
      padding: 10rpx 0;
      width: calc(100% / 5);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

    .navbar-icon {
      width: 70rpx;
      height: 70rpx;
      border-radius: 50%;
      background-color: #f5f6f8;
      margin-bottom: 10rpx;
    }

    .navbar-name {
    }
  }

  .poster-main {
    padding: 0 20rpx;

    .poster {
      width: 100%;
      height: 200rpx;
    }
  }

  .p-t80 {
    padding-top: 80rpx;
  }

  .product-main {
    background-color: #f0f0f0;
    padding-bottom: 20rpx;

    .product-navbar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      transition: all ease 0.3s;

      &.navbar-fixed {
        position: fixed;
        left: 0;
        right: 0;
        top: 280rpx;
        background-color: #f0f0f0;
        z-index: 10;
      }

      .navbar-item {
        width: calc(100% / 4);
        height: 80rpx;
        text-align: center;
        line-height: 80rpx;
        font-size: 30rpx;
        position: relative;

        &.active {
          color: #3cb9ef;

          &::after {
            content: "";
            position: absolute;
            left: 50%;
            bottom: 0;
            transform: translateX(-50%);
            width: 60%;
            height: 6rpx;
            background-color: #3cb9ef;
            border-radius: 0 0 4rpx 4rpx;
          }
        }
      }
    }

    .product-list {
      padding: 20rpx;
      // 	display: flex;
      // 	flex-wrap: wrap;
      // 	justify-content: space-between;

      // 	.product-item {
      // 		width: 50%;

      .demo-warter {
        border-radius: 8px;
        background-color: #ffffff;
        padding: 8px;
        position: relative;
        margin: 10rpx;
      }

      .demo-image {
        width: 100%;
        height: 300rpx;
        border-radius: 4px;
      }

      .demo-title {
        font-size: 30rpx;
        margin-top: 5px;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        overflow: hidden;
      }

      .sub_title {
        color: #999999;
        font-size: 24rpx;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }

      .product-bottom {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .demo-price {
          font-size: 30rpx;
          color: #ff0000;
          margin-top: 5px;
        }
      }

      .demo-shop {
        font-size: 22rpx;
        // color: $up-tips-color;
        margin-top: 5px;
      }
    }

    // 	}
  }

  .minus {
    width: 44rpx;
    height: 44rpx;
    border-width: 1px;
    border-color: #999999;
    border-style: solid;
    border-top-left-radius: 100px;
    border-top-right-radius: 100px;
    border-bottom-left-radius: 100px;
    border-bottom-right-radius: 100px;
    @include flex;
    justify-content: center;
    align-items: center;
  }

  .qty-input {
    text-align: center;
    padding: 0 10px;
    color: #000;
    font-size: 28rpx;
    display: inline-block;
  }

  .plus {
    width: 44rpx;
    height: 44rpx;
    background-color: #3cb9ef;
    border-radius: 50%;
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    justify-content: center;
    align-items: center;
  }
}
</style>
